// 网关设置
import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { FriendService } from './friend.service';
import { ForbiddenException } from '@nestjs/common';
@WebSocketGateway(3001, { transports: ['websocket'], cors: { origin: '*' } })
export class SocketGateway {
  constructor(private readonly friendService: FriendService) {}

  @WebSocketServer() server: Server;

  // 监听发送消息
  @SubscribeMessage('connection')
  async connection(client: Socket, payload: any) {
    console.log('连接成功');
  }

  // 监听发送消息
  @SubscribeMessage('msgToServer')
  async handleMessage(client: Socket, payload: any) {
    const { type, toUser } = payload;
    const toSocketId = await this.friendService.getChat(toUser + '');
    if (type === 'chat') {
      client.to(toSocketId).emit('msgToClient', payload);
    } else {
      client.to(toSocketId).emit('msgPushClient', payload);
    }
    this.friendService.addMessage(payload);
  }
  // 好友申请
  @SubscribeMessage('applyFriend')
  async apply(client: Socket, payload: any) {
    const { user, friend } = payload;
    const count = await this.friendService.apply(payload, 'apply');
    console.log('count', count);
    if (count > 0) {
      throw new ForbiddenException('当前用户已经是你好友');
    }
    const socketId = await this.friendService.getChat(friend + '');
    const myInfo = await this.friendService.findUser(user);
    if (socketId) {
      client.to(socketId).emit('pushToClient', {
        user: friend,
        friend: user,
        friendDetail: myInfo,
      });
    }
  }

  @SubscribeMessage('bindUser')
  bindUser(client: Socket, payload: any) {
    return this.friendService.setChat(payload);
  }

  // 某人加入某Room
  @SubscribeMessage('joinRoom')
  public joinRoom(client: Socket, payload: any): void {
    client.join(payload.id);
  }

  // 某人离开某Room
  @SubscribeMessage('leaveRoom')
  public leaveRoom(client: Socket, payload: any): void {
    client.leave(payload.id);
  }
  afterInit() {
    console.log('afterInit');
  }
  // 链接成功
  handleConnection(val) {
    console.log('handleConnection', val.id);
  }
  // 断开链接
  handleDisconnect() {
    console.log('handleDisconnect');
  }
}
